package com.ljx.rag.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@EnableAsync
@Configuration
public class TaskPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        int availableProcessors = Runtime.getRuntime().availableProcessors(); // 自己机器的核数
        ThreadPoolExecutor  executor = new ThreadPoolExecutor (
                availableProcessors + 1,
                availableProcessors * 4,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(availableProcessors * 100),
                runnable -> {
                    Thread thread = Executors.defaultThreadFactory().newThread(runnable);
                    thread.setName("my-thread-pool" + thread.getId());
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return executor;
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(availableProcessors + 1);
        executor.setMaxPoolSize(availableProcessors * 4);
        executor.setQueueCapacity(availableProcessors * 100);
        executor.setThreadNamePrefix("async-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
